package org.jmc.refmanager.web.wicket.provider;

import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.Adresse;
import org.jmc.refmanager.domain.service.AdresseManager;
import org.jmc.refmanager.web.wicket.model.AdresseModel;

public class AdresseSortableDataProvider extends SortableDataProvider<Adresse> {
	private static final long serialVersionUID = 1L;

	@SpringBean(name="adresseManager")
	private AdresseManager adresseManager;

	private QueryParam<Adresse> queryParameters;
	
	/**
	 * 
	 */
	public AdresseSortableDataProvider(QueryParam<Adresse> params) {
		super();
		InjectorHolder.getInjector().inject(this);
		this.queryParameters = params;
	}

	@Override
	public Iterator<Adresse> iterator(int first, int count) {
		SortParam sortParam = getSort();
		if (this.queryParameters == null) {
			this.queryParameters = new QueryParam<Adresse>();
		}
		
		if (sortParam != null) {
			this.queryParameters.setSortAsc(sortParam.isAscending());
			this.queryParameters.setSortPropertyName(sortParam.getProperty());
		}
		
		this.queryParameters.setFirst(first);
		this.queryParameters.setCount(count);

		return adresseManager.list(this.queryParameters).iterator();
	}

	@Override
	public IModel<Adresse> model(Adresse adresse) {
		return new AdresseModel(adresse);
	}

	@Override
	public int size() {
		if (queryParameters.getCriteriaExample() == null) {
			return 0;
		} else {
			return adresseManager.count(this.queryParameters);
		}
	}

}
